<?php
namespace App\Service\Pay;

use App\Facade\Http;

class Request extends Base
{
    // 请求数据
    protected $data = [];
    
    public function __construct($data = [])
    {
        $this->data = $data;
    }
    
    // 请求头认证
    protected function headerAuth()
    {
        // 头参数
        $header = [
            'AppId'     => $this->getConfig('appid'),
            'Timestamp' => date('YmdHis'),
            'Nonce'     => $this->getRand()
        ];
        
        // 生成签名
        $header['Signature'] = $this->headerAuthSign($header);
        
        // 循环拼接
        foreach($header as $key => $value)
        {
            $header[$key] = '"' . $value . '"';
        }
        
        return 'OPEN-BODY-SIG ' . $this->makeParame($header, ',');
    }
    
    // 请求头认证签名
    protected function headerAuthSign($header)
    {
        // 消息体加密
        $body = $this->shaHex($this->makeJson($this->data));
        
        // 待签名
        $sign = '';
        
        // 拼接请求头
        foreach($header as $value)
        {
            $sign .= $value;
        }
        
        // 连接消息体加密
        return $this->shaHmac($sign . $body);
    }
    
    // 请示
    public function send()
    {
        // 加载请求网址
        $http = Http::create([
            'base_uri' => $this::URL,
        ]);
        
        $data = [
            'json' => $this->data,
            'headers' => [
                'Authorization' => $this->headerAuth()
            ]
        ];

        // 开始请示
        $response = $http->post($this->url, $data);
        
        return json_decode((string) $response->getBody(), true);
    }
    
    // 设置数据
    public function set($key, $data)
    {
        $this->data[$key] = $data;
        
        return $this;
    }
    
    // 设置请求时间
    public function setRequestTime()
    {
        return $this->set('requestTimestamp', date('Y-m-d H:i:s'));
    }
    
    // 设置mid
    public function setMid()
    {
        return $this->set('mid', $this->getConfig('mid'));
    }
    
    // 设置tid
    public function setTid()
    {
        return $this->set('tid', $this->getConfig('tid'));
    }
    
    // 设置 instMid
    public function setInstMid()
    {
        return $this->set('instMid', 'APPDEFAULT');
    }
    
    // 设置订单号
    public function setOrderId()
    {
        return $this->set('merOrderId', $this->getConfig('msgSrcId') . date('YmdHis') . $this->getRand(10));
    }
    
    // 传入金额
    public function setMoney($money)
    {
        return $this->set('totalAmount', (int) ($money * 100));
    }
    
    // 回调地址
    public function setNotify($url)
    {
        return $this->set('notifyUrl', $url);
    }
}